package first.servlet;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class SecurityFilter implements Filter {
    private ServletContext servletContext;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        servletContext = filterConfig.getServletContext();
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        final HttpServletRequest req = (HttpServletRequest) request;
        final HttpServletResponse resp = (HttpServletResponse) response;

       if (
        		req.getRequestURI().equals("/index.html")&&
        		(!Boolean.TRUE.equals(req.getSession(true).getAttribute(ServletAuth.SESS_AUTH)))
        	
        	)
        {
        	servletContext.getRequestDispatcher("/login.jspx").forward(req, resp);
        }
        else
        {
        	if (
        			!Boolean.TRUE.equals(req.getSession(true).getAttribute(ServletAuth.SESS_AUTH)) &&
        			!(req.getRequestURI().equals("/login.jspx") || req.getRequestURI().equals("/login.do")) 
        	) {
        		//resp.sendRedirect("login.html");
        		//  mime-type information collides with resource extension
        		servletContext.getRequestDispatcher("/login.jspx").forward(req, resp);
        		return;
        	}
        }

        //servletContext.getRequestDispatcher("/login.jspx").forward(req, resp);
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        //  nothing to do here
    }
}
